package com.ruoyi.psi.purchase.pay.service;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.psi.purchase.order.domain.PurchaseOrder;
import com.ruoyi.psi.purchase.order.domain.PurchaseOrderList;
import com.ruoyi.psi.purchase.order.mapper.PurchaseOrderMapper;
import com.ruoyi.psi.purchase.order.service.IPurchaseOrderService;
import com.ruoyi.psi.purchase.pay.domain.PurchasePay;
import com.ruoyi.psi.purchase.pay.domain.PurchasePayList;
import com.ruoyi.psi.purchase.pay.mapper.PurchasePayMapper;
import com.ruoyi.psi.purchase.purchasereturn.domain.PurchaseReturnList;
import com.ruoyi.psi.purchase.purchasereturn.service.IPurchaseReturnService;
import com.ruoyi.psi.purchase.storage.service.IPurchaseStorageService;
import com.ruoyi.utils.ID.IdUtil;
import com.ruoyi.utils.UtilsList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * 采购付款/委外付款
 * 业务层执行
 * @author Drj 2021/6/28
 * 修改：lsy 2021.7.17
 */
@Service
public class PurchasePayServiceImpl implements IPurchasePayService {
    @Autowired
    private PurchasePayMapper purchasePayMapper;
    @Autowired
    private IPurchaseOrderService purchaseOrderService;
    @Autowired
    private PurchaseOrderMapper purchaseOrderMapper;
    @Autowired
    private IdUtil idUtil;

    /**
     * 查询所有采购付款
     *
     * @param purchasePay 搜索条件
     * @return
     */
    @Override
    public List<PurchasePay> selectPurchasePayList(PurchasePay purchasePay) {
        List<PurchasePay> purchasePays = savePurchasePayLists(purchasePayMapper.selectPurchasePayList(purchasePay));
        return purchasePays;
    }
    /**
     * 存入对应采购付款详细
     * @param purchasePays 采购付款数组
     * @return
     */
    public List<PurchasePay> savePurchasePayLists(List<PurchasePay> purchasePays){
        for (int i = 0; i < purchasePays.size(); i++) {
            //存入对应采购付款详细
            purchasePays.get(i).setPurchasePayLists(setOtherParameters(purchasePayMapper.selectPurchasePayListListById(purchasePays.get(i).getPurchasePayId())));
        }
        return purchasePays;
    }

    /**
     * 存入入库金额，已付款金额
     * @param purchasePayLists 采购付款详细数组
     * @return
     */
    public List<PurchasePayList> setOtherParameters(List<PurchasePayList> purchasePayLists){
        for (PurchasePayList p : purchasePayLists) {
            switch (p.getPayType()) {
                case "0":
                    PurchaseOrder purchaseOrder = purchaseOrderService.selectPurchaseOrderById(p.getPurchaseOrderId());
                    //订单入库金额
                    p.setPurchaseStoragePrice(purchaseOrder.getPurchaseStoragePriceTotal());
                    //单据总额
                    p.setPurchasePriceTotal(purchaseOrder.getPurchasePriceTotal());
                    break;
                case "1":
                    //采购退货总金额，此时入库金额与的单据金额相同
                    p.setPurchasePriceTotal(-purchasePayMapper.getBillNum(p.getPurchaseOrderId()));
                    p.setPurchaseStoragePrice(-purchasePayMapper.getBillNum(p.getPurchaseOrderId()));
                    break;
            }
            BigDecimal amountPaid = BigDecimal.valueOf(purchasePayMapper.getAmountPaid(p.getPurchaseOrderId(), p.getPayType()));
            //已付金额
            p.setAmountPaid(amountPaid.doubleValue());
        }
        return purchasePayLists;
    }

    /**
     * 根据编号查询
     *
     * @param purchasePayId 采购付款编号
     * @return
     */
    @Override
    public PurchasePay selectPurchasePayById(String purchasePayId) {
        return purchasePayMapper.selectPurchasePayById(purchasePayId);
    }

    /**
     * 新增采购付款
     *
     * @param purchasePay
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertPurchasePay(PurchasePay purchasePay) throws Exception{
        String purchasePayId = idUtil.createPurchasePayId();//自动生成编号
        if(StringUtils.isNotNull(purchasePayMapper.selectPurchasePayById(purchasePay.getPurchasePayId())) || StringUtils.isNull(purchasePay.getPurchasePayLists())){
            //已存在编号或无采购付款详细
            return 0;
        }
        purchasePay.setPurchasePayId(purchasePayId);//主表添加编号
        purchasePayMapper.insertPurchasePay(purchasePay);
        for (int i = 0; i < purchasePay.getPurchasePayLists().size(); i++) {
            purchasePay.getPurchasePayLists().get(i).setPurchasePayId(purchasePayId);//子表添加编号
            purchasePayMapper.insertPurchasePayList(purchasePay.getPurchasePayLists().get(i));
            //判断订单付款状态的修改
            PurchaseOrder purchaseOrder = purchaseOrderService.selectPurchaseOrderById(purchasePay.getPurchasePayLists().get(i).getPurchaseOrderId());
            if (purchaseOrder.getPurchasePriceTotal() - purchasePay.getPurchasePayLists().get(i).getAmountPaid() <= purchasePay.getPurchasePayLists().get(i).getPayAmount()) {
                //订单总额 - 已付款金额 <= 此次付款
                purchaseOrderMapper.updatePaymentStatus(purchasePay.getPurchasePayLists().get(i).getPurchaseOrderId());
            }
        }
        return 1;


    }

    /**
     * 更新采购付款
     *
     * @param purchasePay
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updatePurchasePay(PurchasePay purchasePay) throws Exception{
        if(!StringUtils.isNotNull(purchasePayMapper.selectPurchasePayById(purchasePay.getPurchasePayId())) || StringUtils.isNull(purchasePay.getPurchasePayLists())){
            //不存在编号或无采购付款详细
            return 0;
        }
        purchasePayMapper.updatePurchasePay(purchasePay);
        List<PurchasePayList> purchasePayListsOld = purchasePayMapper.selectPurchasePayListListById(purchasePay.getPurchasePayId());
        List<PurchasePayList> purchasePayListsNew = purchasePay.getPurchasePayLists();
        for (int i = 0; i < purchasePayListsNew.size(); i++) {
            //查询数据库此条采购详细是否存在
            PurchasePayList purchasePayList = purchasePayMapper.selectPurchasePayListById(purchasePayListsNew.get(i));
            if (StringUtils.isNotNull(purchasePayList)){
                //存在
                for (int j = 0; j < purchasePayListsOld.size(); j++) {
                    if (purchasePayListsOld.get(j).getPurchaseOrderId().equals(purchasePayList.getPurchaseOrderId())){
                        //移除旧有中相同部分
                        purchasePayListsOld.remove(j);
                        break;
                    }
                }
                //更新
                purchasePayMapper.updatePurchasePayList(purchasePayListsNew.get(i));
            }else {
                //不存在，新增
                purchasePayMapper.insertPurchasePayList(purchasePayListsNew.get(i));
            }
        }
        for (int i = 0; i < purchasePayListsOld.size(); i++) {
            purchasePayMapper.deletePurchasePayList(purchasePayListsOld.get(i));
        }
        return 1;


    }

    /**
     * 删除采购付款
     *
     * @param purchasePay
     * @return
     */
    @Override
    public int updatePurchasePayDeleteFlag(PurchasePay purchasePay) {
        return purchasePayMapper.updatePurchasePayDeleteFlag(purchasePay);
    }

    /**
     * 新增付款单时查询对应采购订单、采购退货（委外订单暂定）
     *
     * @param supplierInfoId
     * @return
     */
    @Override
    public List<PurchasePayList> getPayBill(String supplierInfoId) {
        List<PurchasePayList> purchasePayLists = purchasePayMapper.getPayBill(supplierInfoId);
        for (PurchasePayList purchasePayList : purchasePayLists) {
            switch (purchasePayList.getPayType()) {
                case "0":
                    PurchaseOrder purchaseOrder = purchaseOrderService.selectPurchaseOrderById(purchasePayList.getPurchaseOrderId());
                    //订单入库金额
                    purchasePayList.setPurchaseStoragePrice(purchaseOrder.getPurchaseStoragePriceTotal());
                    //单据总额
                    purchasePayList.setPurchasePriceTotal(purchaseOrder.getPurchasePriceTotal());
                    break;
                case "1":
                    //采购退货总金额，此时入库金额与的单据金额相同
                    purchasePayList.setPurchasePriceTotal(-purchasePayMapper.getBillNum(purchasePayList.getPurchaseOrderId()));
                    purchasePayList.setPurchaseStoragePrice(-purchasePayMapper.getBillNum(purchasePayList.getPurchaseOrderId()));
                    break;
            }

            BigDecimal amountPaid = BigDecimal.valueOf(purchasePayMapper.getAmountPaid(purchasePayList.getPurchaseOrderId(), purchasePayList.getPayType()));
            //已付金额
            purchasePayList.setAmountPaid(amountPaid.doubleValue());
            //本次付款金额
            purchasePayList.setPayAmount(purchasePayList.getPurchasePriceTotal() - amountPaid.doubleValue());
        }
        return purchasePayLists;
    }
}
